package lar.system.sound;

import lar.system.engine.MainProgram;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.util.Log;

public class Music 
{
	private static MediaPlayer music=null;
	private static int playing=0;
	private static float fadeOutValue = 1.0f;
	private static int swapResId = 0;
	
	public static synchronized void pause()
	{
		if(music != null) music.pause();
	}
	
	public static synchronized void resume()
	{
		if(music != null) music.start();
	}
	
	public static boolean isMusic()
	{
		return music != null;
	}
	
	public static synchronized void setMusic(int resId)
	{
		if(!MainProgram.currentActivity.getPreferences(Context.MODE_PRIVATE).getBoolean("MUSIC", false)) return;
		if(music == null) 
		{
			
			music = Sound.playSound(resId, new OnCompletionListener() 
			{
				public void onCompletion(MediaPlayer mp) 
				{
					
				}
			});
			playing = resId;
			if(music == null) return;
			music.setVolume(0.35f, 0.35f);
			music.setLooping(true);
		}
		
		else 
		{
			if(playing == resId) return;
			swapResId = resId;
			fadeOutValue = 0.35f;
		}
		
	}
	
	public static synchronized void stop()
	{
		if(music != null)
		{
			music.stop();
			music.release();
			music = null;
		}
	}
	
	public static synchronized void endFrame()
	{
		if(music == null) return;
		if(swapResId != 0)
		{
			fadeOutValue -= 0.005f;
			if(fadeOutValue <= 0)
			{
				stop();
				music = null;
				playing = 0;
				setMusic(swapResId);
				swapResId = 0;
			}
			else music.setVolume(fadeOutValue, fadeOutValue);
		}
	}

}
